package com.yuanqi.repository;

import com.yuanqi.domain.OrderTracking;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单跟踪数据访问层
 */
@Repository
public interface OrderTrackingRepository extends JpaRepository<OrderTracking, Long> {
    
    /**
     * 根据订单ID查找跟踪记录
     */
    List<OrderTracking> findByOrderIdOrderByTimestampAsc(Long orderId);
    
    /**
     * 根据状态类型查找跟踪记录
     */
    List<OrderTracking> findByStatusTypeOrderByTimestampDesc(String statusType);
    
    /**
     * 根据操作员查找跟踪记录
     */
    List<OrderTracking> findByOperatorIdOrderByTimestampDesc(Long operatorId);
    
    /**
     * 根据日期范围查找跟踪记录
     */
    @Query("SELECT ot FROM OrderTracking ot WHERE ot.timestamp BETWEEN :startDate AND :endDate ORDER BY ot.timestamp DESC")
    List<OrderTracking> findByTimestampBetween(@Param("startDate") LocalDateTime startDate, 
                                               @Param("endDate") LocalDateTime endDate);
    
    /**
     * 查找订单的最新跟踪记录
     */
    @Query("SELECT ot FROM OrderTracking ot WHERE ot.orderId = :orderId ORDER BY ot.timestamp DESC")
    List<OrderTracking> findLatestByOrderId(@Param("orderId") Long orderId);
    
    /**
     * 查找订单的最新状态
     */
    @Query("SELECT ot FROM OrderTracking ot WHERE ot.orderId = :orderId ORDER BY ot.timestamp DESC")
    OrderTracking findLatestStatusByOrderId(@Param("orderId") Long orderId);
    
    /**
     * 统计今日跟踪记录数量
     */
    @Query("SELECT COUNT(ot) FROM OrderTracking ot WHERE DATE(ot.timestamp) = CURRENT_DATE")
    Long countTodayTracking();
    
    /**
     * 查找进行中的订单
     */
    @Query("SELECT DISTINCT ot.orderId FROM OrderTracking ot WHERE ot.statusType IN ('Pending', 'Processing', 'Shipped')")
    List<Long> findActiveOrderIds();
    
    /**
     * 查找今日配送的订单
     */
    @Query("SELECT DISTINCT ot.orderId FROM OrderTracking ot WHERE ot.statusType = 'Shipped' AND DATE(ot.timestamp) = CURRENT_DATE")
    List<Long> findTodayDeliveryOrderIds();
    
    /**
     * 根据订单类型查找跟踪记录（兼容性方法）
     */
    @Query("SELECT ot FROM OrderTracking ot WHERE ot.statusType = :orderType ORDER BY ot.timestamp DESC")
    List<OrderTracking> findByOrderTypeOrderByTimestampDesc(@Param("orderType") String orderType);
    
    /**
     * 根据状态查找跟踪记录（兼容性方法）
     */
    @Query("SELECT ot FROM OrderTracking ot WHERE ot.statusType = :status ORDER BY ot.timestamp DESC")
    List<OrderTracking> findByStatusOrderByTimestampDesc(@Param("status") String status);
}